package biz.inspeed.test.concurrent;

import java.util.Calendar;
import java.util.UUID;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayMainTest1 {

	public static void main(String[] args) {
		DelayQueue<Product> queue = new DelayQueue<Product>();
		new Thread(new Con1(queue)).start();
		for(int i = 0;i < 12000; i ++){
			queue.put(new Product(String.valueOf(i)));
		}
	}

}

class Con1 implements Runnable {
	DelayQueue<Product> queue = new DelayQueue<Product>();

	public Con1(DelayQueue<Product> queue) {
		this.queue = queue;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Calendar c = Calendar.getInstance();
				String str = String.format("尝试取出产品 %tT\t....", c);
				System.out.println(str);
				Product p = queue.take();
				c = Calendar.getInstance();
				str = String.format("取出产品 %tT\t", c);
				System.out.println(str + p);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

class Product implements Delayed {
	String name = "name";
	String uuid = UUID.randomUUID().toString();
	long insertTime = System.currentTimeMillis();
	static int count = 0;
	int index = 0;
	public Product(String name) {
		this.name = name;
		index = count ++;
	}

	@Override
	public int compareTo(Delayed o) {
		return (int) (getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));//name.compareTo(p.getName());
	}

	@Override
	public long getDelay(TimeUnit unit) {
		long tmp = computeDelay(index);
		return tmp;
	}

	public String getName() {
		return name;
	}

	public String getUuid() {
		return uuid;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}
	
	@Override
	public String toString() {
		String str = "Product(" + name +"," + uuid + ")" ;
		return str;
	}
	
	private long computeDelay(long time){
		///For example, to convert 10 minutes to milliseconds, use: TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)
		 time = TimeUnit.MILLISECONDS.convert ( time , TimeUnit.SECONDS );
		long temp = insertTime -System.currentTimeMillis () + time;
		return temp;
	}
}
